package middleware

import (
	"errors"
	"fmt"
	"runtime/debug"

	"gin-gateway/core/init"
	"github.com/gin-gonic/gin"
)

// RecoveryMiddleware捕获所有panic，并且返回错误信息
func RecoveryMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				//先做一下日志记录
				traceContext := Init.TraceFromGinContext(c)
				Init.Log.TagError(traceContext, "_com_panic", map[string]interface{}{
					"error": fmt.Sprint(err),
					"stack": string(debug.Stack()),
				})

				if Init.BaseCfg.DebugMode != "debug" {
					ResponseError(c, 5001, errors.New("内部错误"))
				} else {
					ResponseError(c, 5002, errors.New(fmt.Sprint(err)))
				}
				fmt.Println("recovery2<<<<<")
				response, _ := c.Get("response")
				c.JSON(500, response)
			}
		}()
		c.Next()
	}
}
